package formula.business.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import formula.business.model.Driver;
import formula.business.model.Level;
import formula.business.model.Team;

/**
 * @author Gauthier Peel
 */
@Repository("loadDao")
@Transactional
public class LoadDaoJpaImpl implements LoadDao {

	@PersistenceContext
	protected EntityManager em;
	private static String[] tables = { "Driver", "Level", "Team", };

	@Override
	public void unload() {
		for (String table : tables) {
			em.createQuery("delete from " + table).executeUpdate();
		}
	}

	@Override
	public void load() {
		Level ex = new Level("Expert");
		em.persist(ex);
		Level in = new Level("Intermediate");
		em.persist(in);
		Level ne = new Level("Newbie");
		em.persist(ne);
		//
		Team ferrari = new Team("Ferrari");
		em.persist(ferrari);
		Team ml = new Team("McLaren");
		em.persist(ml);
		//
		em.flush();
		//
		char[] tabchar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
		for (int i = 0; i < 10; i++) {
			Driver p = new Driver(tabchar[9 - i] + "_driver_intermediate");
			p.setLevel(in);
			p.setBirthdate(new Date());
			p.setAge(10);
			p.setFirstname(tabchar[i] + "Johnson");
			em.persist(p);
		}
		for (int i = 0; i < 10; i++) {
			Driver p = new Driver(tabchar[i] + "_driver_newbie");
			p.setLevel(ne);
			p.setBirthdate(new Date());
			p.setAge(10);
			p.setFirstname(tabchar[9 - i] + "_Guillaume");
			em.persist(p);
		}
		for (int i = 0; i < 10; i++) {
			Driver p = new Driver(tabchar[i] + "_driver_expert");
			p.setLevel(ex);
			p.setBirthdate(new Date());
			p.setAge(10);
			p.setFirstname(tabchar[9 - i] + "_Julien");
			em.persist(p);
		}
		em.flush();
		//
		Driver button = new Driver("Button");
		button.setLevel(in);
		button.setBirthdate(new Date());
		button.setAge(10);
		button.setFirstname("Johnson");
		button.setTeam(ml);
		em.persist(button);
		//
		Driver d2 = new Driver("Massa");
		d2.setLevel(ex);
		d2.setBirthdate(new Date());
		d2.setAge(20);
		d2.setFirstname("Felipe");
		d2.setTeam(ferrari);
		em.persist(d2);
		//
		Driver d3 = new Driver("Alonso");
		d3.setLevel(ne);
		d3.setBirthdate(new Date());
		d3.setAge(10);
		d3.setFirstname("Fernando");
		d3.setTeam(ferrari);
		em.persist(d3);
	}

	@Override
	public List<Driver> selectDrivers() {
		List<Driver> list = em.createQuery("from Driver as p left join fetch p.level left join fetch p.team",
				Driver.class).getResultList();
		return list;
	}

	@Override
	public List<Driver> selectDriversNoFetch() {
		List<Driver> list = em.createQuery("from Driver", Driver.class).getResultList();
		return list;
	}
}
